package org.jeecg.modules.power.controller;

import java.security.KeyManagementException;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import javax.net.ssl.SSLContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.bind.DatatypeConverter;


import cn.hutool.json.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpResponseException;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ssl.TrustSelfSignedStrategy;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.ssl.SSLContexts;
import org.apache.http.util.EntityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.power.entity.PowerLog;
import org.jeecg.modules.power.entity.PowerOn;
import org.jeecg.modules.power.entity.PowerSwitch;
import org.jeecg.modules.power.mapper.PowerSwitchMapper;
import org.jeecg.modules.power.service.IPowerLogService;
import org.jeecg.modules.power.service.IPowerOnService;
import java.util.Date;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecg.modules.power.service.IPowerSwitchService;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;
import com.alibaba.fastjson.JSON;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

 /**
 * @Description: 子控
 * @Author: jeecg-boot
 * @Date:   2024-03-25
 * @Version: V1.0
 */
@Slf4j
@Api(tags="子控")
@RestController
@RequestMapping("/power/powerOn")
public class PowerOnController extends JeecgController<PowerOn, IPowerOnService> {
	@Autowired
	private IPowerOnService powerOnService;

	 @Autowired
	 private IPowerSwitchService powerSwitchService;
	 private String ddkurl = "https://openapi.devcld.com/";

	 @Autowired
	 private IPowerLogService powerLogService;

	 @Autowired
	 private PowerSwitchMapper powerSwitchMapper;
	/**
	 * 分页列表查询
	 *
	 * @param powerOn
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	@AutoLog(value = "子控-分页列表查询")
	@ApiOperation(value="子控-分页列表查询", notes="子控-分页列表查询")
	@GetMapping(value = "/list")
	public Result<?> queryPageList(PowerOn powerOn,
								   @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
								   @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
								   HttpServletRequest req) {
		QueryWrapper<PowerOn> queryWrapper = QueryGenerator.initQueryWrapper(powerOn, req.getParameterMap());
		if(powerOn.getSid()==null){
			return Result.error("没有可用的设备id");
		}
		Page<PowerOn> page = new Page<PowerOn>(pageNo, pageSize);

		IPage<PowerOn> pageList = powerOnService.page(page, queryWrapper);
		return Result.ok(pageList);
	}



	/**
	 * 添加
	 *
	 * @param powerOn
	 * @return
	 */
	@AutoLog(value = "子控-添加")
	@ApiOperation(value="子控-添加", notes="子控-添加")
	@PostMapping(value = "/add")
	public Result<?> add(@RequestBody PowerOn powerOn) {
		powerOnService.save(powerOn);
		return Result.ok("添加成功！");
	}
	
	/**
	 * 编辑
	 *
	 * @param powerOn
	 * @return
	 */
	@AutoLog(value = "子控-编辑")
	@ApiOperation(value="子控-编辑", notes="子控-编辑")
	@PutMapping(value = "/edit")
	public Result<?> edit(@RequestBody PowerOn powerOn) {
		powerOnService.updateById(powerOn);
		return Result.ok("编辑成功!");
	}
	
	/**
	 * 通过id删除
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "子控-通过id删除")
	@ApiOperation(value="子控-通过id删除", notes="子控-通过id删除")
	@DeleteMapping(value = "/delete")
	public Result<?> delete(@RequestParam(name="id",required=true) String id) {
		powerOnService.removeById(id);
		return Result.ok("删除成功!");
	}
	
	/**
	 * 批量删除
	 *
	 * @param ids
	 * @return
	 */
	@AutoLog(value = "子控-批量删除")
	@ApiOperation(value="子控-批量删除", notes="子控-批量删除")
	@DeleteMapping(value = "/deleteBatch")
	public Result<?> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
		this.powerOnService.removeByIds(Arrays.asList(ids.split(",")));
		return Result.ok("批量删除成功！");
	}
	
	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "子控-通过id查询")
	@ApiOperation(value="子控-通过id查询", notes="子控-通过id查询")
	@GetMapping(value = "/queryById")
	public Result<?> queryById(@RequestParam(name="id",required=true) String id) {
		PowerOn powerOn = powerOnService.getById(id);
		return Result.ok(powerOn);
	}

	 @AutoLog(value = "设备数据下发")
	 @ApiOperation(value="设备数据下发", notes="设备数据下发")
	 @PostMapping(value = "/zkswitch")
	 public Result<?> zkswitch(@RequestBody PowerOn powerOn) throws NoSuchAlgorithmException, KeyStoreException, KeyManagementException, UnsupportedEncodingException {
		 // 创建HttpClient对象 get请求 https的请求 带有basic认证的

		 PowerLog powerLog = new PowerLog();

		 powerLog.setSid(powerSwitchMapper.getId(powerOn.getDdkid()));
		 powerLog.setZkname(powerOn.getNum()+","+powerOn.getName());
		 powerLog.setOnoff(powerOn.getOnoff());
		 powerLogService.save(powerLog);
		 SSLContext sslContext = SSLContexts.custom().loadTrustMaterial(null, new TrustSelfSignedStrategy()).build();
		 CloseableHttpClient httpClient = HttpClients.custom().setSSLContext(sslContext).build();
		 //创建get请求对象
		 HttpPost httpPost = new HttpPost(ddkurl + "/device/rest/1.0/device/writeReg" );
		 //接口有basic认证，Username是a9dc0e17001a401384a253794c7719ad, Password是b89ce8c6040d4bd8b4f1ac2c7765ad1f
		 String encoding = DatatypeConverter.printBase64Binary("a9dc0e17001a401384a253794c7719ad:b89ce8c6040d4bd8b4f1ac2c7765ad1f".getBytes("UTF-8"));
		 httpPost.setHeader("Authorization", "Basic " + encoding);
		 httpPost.setHeader("Content-Type", "application/json");
		 httpPost.setHeader("Accept-Charset", "UTF-8");
		 try {
			 //设置请求参数
			 JSONObject json = new JSONObject();
			 json.put("deviceId", powerOn.getDdkid());
			 // 创建 regs JSONArray
			 JSONArray regsArray = new JSONArray();
			 // 假设你有一个或多个regs要添加，这里仅举一个例子
			 JSONObject regItem = new JSONObject();
			 regItem.put("addr", powerOn.getNum()); // 假设这是你要设置的地址
			 regItem.put("type", "Bool");
			 regItem.put("value", powerOn.getOnoff().equals("1")); // 如果status等于"1"，则value为false，否则应根据实际情况转换

			 regsArray.put(regItem);

			 // 将regs数组添加到主json对象中
			 json.put("regs", regsArray);

			 StringEntity entity = new StringEntity(json.toString(), "UTF-8");
			 httpPost.setEntity(entity);
			 //执行请求
			 HttpResponse httpResponse = httpClient.execute(httpPost);
			 int statusCode = httpResponse.getStatusLine().getStatusCode();
			 String responseBody = EntityUtils.toString(httpResponse.getEntity());
			 if (statusCode == 200) {
				 return Result.ok("开关成功！");
			 }
		 }catch (Exception e) {
			 e.printStackTrace();
		 }

		return Result.ok("开关成功！");
	 }


	 @ApiOperation(value="子控-通过设备id（内部）查询", notes="子控-通过设备id（内部）查询")
	 @GetMapping(value = "/getZkList")
	 public Result<?> getZkList(@RequestParam(name="sid",required=true) String sid) throws NoSuchAlgorithmException, KeyStoreException, KeyManagementException, IOException {

		 QueryWrapper<PowerOn> queryWrapper = new QueryWrapper<>();
		 queryWrapper.eq("sid",sid);
		 List<PowerOn> powerOnList =powerOnService.list(queryWrapper);
		 PowerSwitch powerSwitch = powerSwitchService.getById(sid);
		 // 创建HttpClient对象 get请求 https的请求 带有basic认证的
		 SSLContext sslContext = SSLContexts.custom().loadTrustMaterial(null, new TrustSelfSignedStrategy()).build();
		 CloseableHttpClient httpClient = HttpClients.custom().setSSLContext(sslContext).build();
		 //创建get请求对象
		 HttpGet httpGet = new HttpGet(ddkurl + "/device/rest/1.0/device/template?ids=" + powerSwitch.getDdkid());
		 //接口有basic认证，Username是a9dc0e17001a401384a253794c7719ad, Password是b89ce8c6040d4bd8b4f1ac2c7765ad1f
		 String encoding = DatatypeConverter.printBase64Binary("a9dc0e17001a401384a253794c7719ad:b89ce8c6040d4bd8b4f1ac2c7765ad1f".getBytes("UTF-8"));
		 httpGet.setHeader("Authorization", "Basic " + encoding);
		 //httpGet.setHeader("Authorization", "Basic YTlkYzBlMTcwMDFhNDAxMzg0YTI1Nzk0Yzc3MTlhZGY6Yjg5Y2U4YzYwNGQ0YmQ4YjRmMWFjMmM3NzY1YWQxZjM=");

		 //设置请求参数
		 httpGet.setHeader("Content-Type", "application/json");
		 httpGet.setHeader("Accept-Charset", "UTF-8");
		 //设置get请求参数
		 HttpResponse httpResponse = httpClient.execute(httpGet);
		//把响应转成json对象
		 String responseBody = EntityUtils.toString(httpResponse.getEntity());
		 JSONObject jsonObject = JSON.parseObject(responseBody);
		 com.alibaba.fastjson.JSONArray dataArray = jsonObject.getJSONArray("data");
		 com.alibaba.fastjson.JSONArray retArr = new com.alibaba.fastjson.JSONArray();
		 if (!dataArray.isEmpty()) {
			 JSONObject dataObject = dataArray.getJSONObject(0);
			 //获取template对象
			 JSONObject templateObject = dataObject.getJSONObject("template");
			 com.alibaba.fastjson.JSONArray regsArray = templateObject.getJSONArray("regs");
			 for (int i = 0; i < regsArray.size(); i++) {
				 JSONObject regObject = regsArray.getJSONObject(i);
				 for (PowerOn powerOn : powerOnList) {
					 if(powerOn.getNum().equals(regObject.getString("addr"))){
						 String name = powerOn.getName();
						 String addr = regObject.getString("addr");
						 JSONObject ret = getReadReg(powerSwitch.getDdkid(),addr,name);
						 ret.put("isjdq",powerOn.getIsjdq());
						 ret.put("id",powerOn.getId());
						 retArr.add(ret);
					 }
				 }
			 }
		 }
		 return Result.ok(retArr);
	 }

	 public JSONObject getReadReg(String ddkid, String num,String name) throws NoSuchAlgorithmException, KeyStoreException, KeyManagementException, IOException {
		 // 创建HttpClient对象 get请求 https的请求 带有basic认证的
		 SSLContext sslContext = SSLContexts.custom().loadTrustMaterial(null, new TrustSelfSignedStrategy()).build();
		 CloseableHttpClient httpClient = HttpClients.custom().setSSLContext(sslContext).build();
		 //创建get请求对象
		 HttpPost httpPost = new HttpPost(ddkurl + "/device/rest/1.0/device/readReg" );
		 //接口有basic认证，Username是a9dc0e17001a401384a253794c7719ad, Password是b89ce8c6040d4bd8b4f1ac2c7765ad1f
		 String encoding = DatatypeConverter.printBase64Binary("a9dc0e17001a401384a253794c7719ad:b89ce8c6040d4bd8b4f1ac2c7765ad1f".getBytes("UTF-8"));
		 httpPost.setHeader("Authorization", "Basic " + encoding);
		 httpPost.setHeader("Content-Type", "application/json");
		 httpPost.setHeader("Accept-Charset", "UTF-8");
		 JSONObject dataObject = new JSONObject();
		 try {
			 //设置请求参数
			 JSONObject json = new JSONObject();
			 json.put("deviceId", ddkid);
			 // 创建 regs JSONArray
			 JSONArray regsArray = new JSONArray();
			 // 假设你有一个或多个regs要添加，这里仅举一个例子
			 JSONObject regItem = new JSONObject();
			 regItem.put("addr", num); // 假设这是你要设置的地址
			 regItem.put("type", "Bool");
			 regsArray.put(regItem);

			 // 将regs数组添加到主json对象中
			 json.put("regs", regsArray);

			 StringEntity entity = new StringEntity(json.toString(), "UTF-8");
			 httpPost.setEntity(entity);
			 //执行请求
			 HttpResponse httpResponse = httpClient.execute(httpPost);
			 String responseBody = EntityUtils.toString(httpResponse.getEntity());
			 JSONObject jsonObject = JSON.parseObject(responseBody);
			 JSONObject data = jsonObject.getJSONObject("data");
			 com.alibaba.fastjson.JSONArray arr = data.getJSONArray("regs");
			 dataObject = arr.getJSONObject(0);
			 dataObject.put("name", name);
		 }catch (Exception e) {
			 e.printStackTrace();
		 }

		 return dataObject;

	 }

}
